/* eslint-disable no-plusplus */
import ElEditable from '@components/el-editable';
import {
  queryOrderInfo,
  stockBatchList,
  orderProductList,
  getOrderDeliverList,
  findPaymentByOrderId,
  getOrderDeliverDetailList,
  findOrderStatus,
  getOrderLogistics,
  orderCancelProductList,
  // orderGetAppendInfo,
  findStockStatus,
  returnStatus
  // queryOrderInfoNew
} from '@api/m_mall_web_v1.js';
import {
  C0LUMNS,
  DELIVERY_ORDER_C0LUMNS,
  RECEIVE_C0LUMNS,
  RECEIVE_COORDINATION,
  SHIPPING_INFORMATION,
  PAY_INFO,
  CANCEL_C0LUMNS,
  STOCK_TYPE
} from './index.const';
// eslint-disable-next-line import/extensions
import step from '~/modules/step';

export default {
  components: {
    ElEditable,
    step
  },
  inject: ['apiMMallWeb'],
  data() {
    return {
      // text: "(去应付账单管理支付)",
      // timeOut: '00:00:00',
      // showTimeOut: true,
      currentPage: 1,
      pageSize: 20,
      receivCurrentPage: 1,
      receivPageSize: 20,
      receivData: {},
      rowData: {},
      receivDataLoading: false,
      tableLoading: false,
      payload: {},
      dialogVisible: false,
      PAY_INFO, // 支付信息
      C0LUMNS,
      CANCEL_C0LUMNS,
      RECEIVE_COORDINATION, // 收货信息表头
      RECEIVE_C0LUMNS, // 收货详情表头
      DELIVERY_ORDER_C0LUMNS, // 出库单表头
      SHIPPING_INFORMATION, // 配送信息表头
      STOCK_TYPE,
      logisticsData: [],
      orderDetail: {},
      orderId: '',
      orderCode: '',
      orderDetailId: '',
      orderType: 1,
      busModel: 1,
      activeName: 'first',
      order_tab: [],
      stepData: [],
      stepData_offline: [],
      stepStr_offline: [],
      stockBatchData: [],
      supplierVo: {},
      addressResDto: {},
      orderAppendPOS: [],
      payDetailData: [],
      orderIdReturn: '',
      orderCodeReturn: '',
      orderIdExchange: '',
      orderCodeExchange: '',
      // 取消产品列表
      cancelTableLoading: false,
      cancelPayload: {},
      cancelContent: [],
      cancelCurrentPage: 1,
      cancelPageSize: 20,
      returnStutas: '', // 退货状态
      exchangeStutas: '' // 换货状态
    };
  },
  created() {
    this.orderId = this.$route.query.id;
    this.orderDetailId = this.$route.query.orderDetailId;
    this.orderCode = this.$route.query.orderCode;
    // this.setTime()

    // 获取步骤条数据
    this.getStepList();
    // 退货/换货按钮展示

    // 根据id获取列表详情
    this.$axios
      .$post(queryOrderInfo, {
        orderId: this.orderId
      })
      .then(res => {
        if (res.code === '0' && res.payload) {
          this.supplierVo = res.payload.supplierVo;
          this.addressResDto = res.payload.addressResDto;
          this.orderAppendPOS = res.payload.orderAppendPOS;
          if (res.payload.orderAppendPOS.length) {
            res.payload.orderAppendPOS.forEach(item => {
              const newItem = item;
              // eslint-disable-next-line no-unused-expressions
              newItem.attributeType === 3 &&
                (newItem.attributeValue = item.selectName);
            });
          }
          this.orderDetail = {
            ...res.payload
          };
          this.orderDetailId = res.payload.orderDetailId;
          this.orderIdReturn = res.payload.orderIdReturn;
          this.orderCodeReturn = res.payload.orderCodeReturn;
          this.orderIdExchange = res.payload.orderIdExchange;
          this.orderCodeExchange = res.payload.orderCodeExchange;
          // this.getAppendInfo(res.payload.contractVo)
          this.getList(res.payload.orderDetailId);
          this.getCancelList(res.payload.orderDetailId);
        }
      });
    // 库存配位
    this.$axios
      .$post(stockBatchList, {
        orderId: this.orderId,
        page: 1,
        pageSize: 99999
      })
      .then(res => {
        if (res.code === '0' && res.payload.content) {
          this.stockBatchData = res.payload.content;
        }
      });
  },
  async mounted() {
    await this.getReturnStatus();
    // const arr = [];
    const btn = {
      type: 'btn',
      arr: []
    };
    btn.arr.push({
      type: 'primary',
      val: '再来一单',
      handle: this.goAdd
    });
    if (this.returnStutas === 1) {
      btn.arr.push({
        type: 'primary',
        disabled: true,
        val: '退货中',
        handle: this.returning
      });
    } else if (this.returnStutas === 2) {
      btn.arr.push({
        type: 'primary',
        val: '申请退货',
        handle: this.applyForReturn
      });
    }
    if (this.exchangeStutas === 1) {
      btn.arr.push({
        type: 'primary',
        disabled: true,
        val: '换货中',
        handle: this.exchangeing
      });
    } else if (this.exchangeStutas === 2) {
      btn.arr.push({
        type: 'primary',
        val: '申请换货',
        handle: this.applyForExchange
      });
    }

    this.$store.commit('changeLayoutHandle', btn);
  },
  methods: {
    // 再来一单
    goAdd() {
      this.$router.push({
        path: '/purchase-order/wholesale/add',
        query: {
          id: this.orderId,
          reAdd: true
        }
      });
    },
    // 退货/换货按钮展示
    getReturnStatus() {
      const params = {
        orderCode: this.orderCode
      };
      return this.$axios.$post(returnStatus, params).then(res => {
        if (res.code === '0') {
          this.returnStutas = res.payload.returnStutas;
          this.exchangeStutas = res.payload.exchangeStutas;
        }
        return Promise.resolve(res);
      });
    },
    // 附加信息转译
    getAppendInfo() {
      // this.$axios.$post(orderGetAppendInfo, {
      //   productLineCode: obj.productLineCode,
      //   vendorNum: obj.supplierCode,
      //   busModel: 1,
      //   page: 1,
      //   pageSize: 9999,
      // }).then(res => {
      //   if (res.code === '0' && res.payload) {
      //     let spliceIndex = []
      //     this.orderAppendPOS.forEach((item, index) => {
      //       res.payload.forEach(it => {
      //         if (item.attributeName === it.attributeName) {
      //           let list = it.valueRange ? JSON.parse(it.valueRange) : []
      //           // let hasOption = false
      //           list.forEach(val => {
      //             if (val.value === item.attributeValue) {
      //               // hasOption = true
      //               item.attributeValue = val.label
      //             }
      //           })
      //           // if (!hasOption) {
      //           //   spliceIndex.indexOf(index) < 0 && spliceIndex.push(index)
      //           // }
      //         }
      //       })
      //     })
      //     // spliceIndex.length && spliceIndex.forEach(sp => {
      //     //   this.orderAppendPOS.splice(sp, 1)
      //     // })
      //   }
      // })
    },
    // setTime() {
    //   const endTime = new Date("2020/07/21 11:09:00").getTime();
    //   const staTime = new Date().getTime()
    //   if (endTime > staTime) {
    //     let that = this
    //     let timer = setInterval(function () {
    //       let time = new Date().getTime()
    //       let time_distance = endTime - time
    //       // 时
    //       var int_hour = Math.floor(time_distance / 3600000);
    //       time_distance -= int_hour * 3600000;
    //       // 分
    //       var int_minute = Math.floor(time_distance / 60000);
    //       time_distance -= int_minute * 60000;
    //       // 秒
    //       var int_second = Math.floor(time_distance / 1000);
    //       // 时分秒为单数时、前面加零
    //       if (int_hour < 10) {
    //         int_hour = "0" + int_hour;
    //       }
    //       if (int_minute < 10) {
    //         int_minute = "0" + int_minute;
    //       }
    //       if (int_second < 10) {
    //         int_second = "0" + int_second;
    //       }
    //       if (int_hour == 0 && int_minute == 0 && int_second == 0) {
    //         that.timeOut = "00:00:00"
    //         clearInterval(timer)
    //         that.text = '已超时，请重新下单'
    //       } else {
    //         that.timeOut = `${int_hour}:${int_minute}:${int_second}`;
    //       }
    //     }, 1000)
    //   } else {
    //     this.text = '(已超时，请重新下单)'
    //   }
    // },
    // 获取两个状态流转接口
    getStepList() {
      this.$axios
        .$post(findOrderStatus, {
          orderId: this.orderId
        })
        .then(res => {
          if (res.code === '0' && res.payload.orderStatusInfoVO) {
            this.stepData = res.payload.orderStatusInfoVO;
          }
        });
      this.$axios
        .$post(findStockStatus, {
          orderId: this.orderId
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            const data = res.payload.orderStatusInfoVO;
            const arr = [];
            const newArr = [];
            data.map(item => {
              if (Number(item.lineNum) === 1) {
                arr.push(item);
              } else {
                newArr.push(item);
              }
              return false;
            });
            arr.sort((a, b) => a.orderStatus - b.orderStatus);
            this.stepData_offline.push(arr);
            if (newArr.length) {
              const num = newArr.length / 2;
              for (let i = 1; i <= num; i++) {
                const itemArr = [];
                newArr.map(item => {
                  if (Number(item.lineNum) === i + 1) {
                    itemArr.push(item);
                  }
                  return false;
                });
                itemArr.sort((a, b) => a.orderStatus - b.orderStatus);
                this.stepData_offline.push(itemArr);
              }
            }
            const str = res.payload.remark ? res.payload.remark.split(',') : [];
            str.map(item => {
              if (this.STOCK_TYPE[item]) {
                this.stepStr_offline.push(this.STOCK_TYPE[item]);
              }
              return false;
            });
          }
        });
    },
    // 表格添加高亮
    // eslint-disable-next-line consistent-return
    tableRowClassName({ row }) {
      if (row.confirmCount) {
        if (row.productCount > row.confirmCount) {
          return 'bgHeight';
        }
      }
    },
    // 订单详情采购产品分页列表
    getList() {
      this.tableLoading = true;
      this.$axios
        .$post(orderProductList, {
          orderDetailId: this.orderDetailId,
          page: this.currentPage,
          pageSize: this.pageSize
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.payload = res.payload;
          }
          this.tableLoading = false;
        });
    },
    // 订单详情采购产品分页列表分页器
    reloadProductData(val) {
      this.currentPage = val.number;
      this.pageSize = val.size;
      this.getList();
    },
    // 取消产品分页器
    cancelReloadProductData(val) {
      this.cancelCurrentPage = val.number;
      this.cancelPageSize = val.size;
      this.getCancelList();
    },
    // 获取取消的产品列表
    getCancelList() {
      this.cancelTableLoading = true;
      this.$axios
        .$post(orderCancelProductList, {
          orderDetailId: this.orderDetailId,
          page: this.cancelCurrentPage,
          pageSize: this.cancelPageSize
        })
        .then(res => {
          if (res.code === '0' && res.payload.content) {
            this.cancelPayload = res.payload;
            this.cancelContent = res.payload.content;
          }
          this.cancelTableLoading = false;
        });
    },
    // 底部tab切换调用不同接口
    handleClick(tab) {
      if (tab.name === 'fourth') {
        this.getOrderDeliverList();
      }
      if (tab.name === 'second') {
        this.getPayment();
      }
      if (tab.name === 'third') {
        this.getLogistics();
      }
    },
    // 支付信息
    getPayment() {
      this.$axios
        .$get(`${findPaymentByOrderId}?orderId=${this.orderId}`)
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.payDetailData = [res.payload];
          }
        });
    },
    // 配送信息
    getLogistics() {
      this.$axios
        .$post(getOrderLogistics, {
          orderCode: this.orderDetail.orderCode
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.logisticsData = res.payload;
          }
        });
    },
    // 收货信息列表
    getOrderDeliverList() {
      this.$axios
        .$get(`${getOrderDeliverList}?orderCode=${this.orderDetail.orderCode}`)
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.order_tab = res.payload;
          }
        });
    },
    showLog(row) {
      this.dialogVisible = true;
      this.rowData = row;
      this.getReceivList();
    },
    // 收货信息-详情列表分页器
    reloadReceiv(val) {
      this.receivCurrentPage = val.number;
      this.receivPageSize = val.size;
      this.getReceivList();
    },
    // 收货信息-详情列表
    getReceivList() {
      this.receivDataLoading = true;
      this.$axios
        .$post(getOrderDeliverDetailList, {
          deliverCode: this.rowData.deliverCode,
          page: this.receivCurrentPage,
          pageSize: this.receivPageSize
        })
        .then(res => {
          if (res.code === '0' && res.payload) {
            this.receivData = res.payload;
          }
          this.receivDataLoading = false;
        });
    },
    // 退货中页面跳转
    returning() {
      this.$router.push({
        path: '/after-sale/order-management/returnDetails',
        query: {
          orderId: this.orderIdReturn,
          orderCode: this.orderCodeReturn
        }
      });
    },
    // 申请退货页面跳转
    applyForReturn() {
      this.$router.push({
        path: '/purchase-order/wholesale/list/return',
        query: {
          orderId: this.orderId,
          orderType: this.orderType
        }
      });
    },
    // 换货中页面跳转
    exchangeing() {
      this.$router.push({
        path: '/after-sale/order-management/returnDetails',
        query: {
          orderId: this.orderIdExchange,
          orderCode: this.orderCodeExchange
        }
      });
    },
    // 申请换货页面跳转
    applyForExchange() {
      this.$router.push({
        path: '/purchase-order/wholesale/list/exchange',
        query: {
          orderId: this.orderId,
          orderType: this.orderType
        }
      });
    }
  }
};
